<template>
	<view>
		<!-- 功能性组件，无UI -->
	</view>
</template>

<script>
import { ChunkRes } from "@/utils/chunkRes.js"
import api from '@/api/index.js'

export default {
	name: 'chat-message-service',
	props: {
		typingInterval: {
			type: Number,
			default: 50
		},
		enableWebSearch: {
			type:Boolean,
		}
	},
	data() {
		return {
			isTyping: false,
			currentMassage: {},
			currentIndex: 0,
			currentContent: '',
			sendState: false
		}
	},
	methods: {
		// 获取模型列表
		async getModelList() {
			try {
				const res = await api.chats.getModelList();
				
				if (Array.isArray(res.modelList)) {
					// 将返回的字符串数组转换为所需格式
					const modelList = res.modelList.map(modelName => ({
						label: modelName,
						value: modelName.toLowerCase().replace(/\s+/g, '-')
					}));
					let currentModel = ''
					if (this.enableWebSearch) {
					 	currentModel= res.agentModel;
					} else {
					 	currentModel= res.model;
					}
					
					// 如果列表为空，设置默认值
					if (modelList.length === 0) {
						modelList = [
							{label: 'GPT-3.5', value: 'gpt-3.5-turbo'},
							{label: 'GPT-4', value: 'gpt-4'},
							{label: 'Claude', value: 'claude'}
						];
					}
					
					// 检查当前选择的模型是否在列表中
					const modelExists = modelList.some(model => model.value === currentModel);
					if (!modelExists && modelList.length > 0) {
						// 如果当前选择的模型不在列表中，选择第一个
						currentModel = modelList[0].value;
					}
					
					return {
						modelList,
						currentModel
					};
				}
			} catch (error) {
				console.error('获取模型列表失败:', error);
				// 设置默认模型列表
				return {
					modelList: [
						{label: 'GPT-3.5', value: 'gpt-3.5-turbo'},
						{label: 'GPT-4', value: 'gpt-4'},
						{label: 'Claude', value: 'claude'}
					],
					currentModel: 'gpt-4'
				};
			}
		},
		
		// 获取联网搜索状态
		async getWebSearchStatus() {
			try {
				const res = await api.chats.getWebSearchStatus();
				return res.enable;
			} catch (error) {
				console.error('获取联网搜索状态失败:', error);
				return false;
			}
		},
		
		// 获取历史消息
		async getHistoryMsg(currentModel, modelList) {
			try {
				const res = await api.chats.getMessageList({
					id: this.enableWebSearch ? uni.getStorageSync('agentSessionId') : uni.getStorageSync('sessionId'),
					page: 1,
					page_size: 10,
					desc: false,
					chatId: uni.getStorageSync('chatId'),
					agentId: uni.getStorageSync('agentId'),
					enableWebSearch:this.enableWebSearch
				});
				
				const list = res[0]?.messages || [];
				// 获取当前选择的模型名称
				const currentModelName = modelList.find(model => model.value === currentModel)?.label || 'AI助手';
				
				return list.map(item => {
					let content = ''
					if (this.enableWebSearch && item.role === 'user') {
						const index = item.content?.indexOf('|')
						content = item.content.substring(index+1) || ''
					} else {
						content = item.content
					}
					return {
						content: content, // 消息内容
						type: item.role === 'user' ? 1 : 0, // 此为消息类别，设 1 为发出去的消息，0 为收到对方的消息,
						state: item.role === 'user' ? 1 : 0,
						icon: item.role === 'user' ? '/static/avatar.png' : '/static/logo.png',
						end: true,
						// 为机器人消息添加模型名称
						...(item.role !== 'user' ? { modelName: currentModelName } : {})
					}
				}).reverse();
			} catch (error) {
				console.error('获取历史消息失败:', error);
				return [];
			}
		},
				
		// 清除聊天记录
		async clearChatHistory() {
			try {
				// 显示加载提示
				uni.showLoading({
					title: '清除中...'
				});
				
				// 调用API清除聊天记录
				const sessionId = uni.getStorageSync('sessionId');
				const agentSessionId = uni.getStorageSync('agentSessionId')
				const result = await api.chats.cleanMessage({
					sessionId,
					agentSessionId,
					enableWebSearch:this.enableWebSearch
				});
				// 如果返回了新的sessionId，更新存储
				if (result) {
					if (this.enableWebSearch) {
						uni.setStorageSync('agentSessionId', result);
					} else {
						uni.setStorageSync('sessionId', result);
					}
					console.log('聊天记录已清除，新的sessionId:', result);
				}
				
				// 隐藏加载提示，显示成功提示
				uni.hideLoading();
				uni.showToast({
					title: '聊天记录已清除',
					icon: 'none'
				});
				
				return true;
			} catch (error) {
				console.error('清除聊天记录失败:', error);
				uni.hideLoading();
				uni.showToast({
					title: '清除失败，请重试',
					icon: 'none'
				});
				return false;
			}
		},
		
		// 切换模型
		async changeModel(model, modelList) {
			try {
				// 显示加载提示
				uni.showLoading({
					title: '切换中...'
				});
				
				// 调用API切换模型
				await api.chats.updateModel(model,this.enableWebSearch);
				
				// 获取新选择的模型名称
				const newModelName = modelList.find(m => m.value === model)?.label || 'AI助手';
				
				// 隐藏加载提示，显示成功提示
				uni.hideLoading();
				uni.showToast({
					title: `已切换至 ${newModelName}`,
					icon: 'none'
				});
				
				return {
					success: true,
					modelName: newModelName
				};
			} catch (error) {
				console.error('切换模型失败:', error);
				uni.hideLoading();
				uni.showToast({
					title: '切换模型失败',
					icon: 'none'
				});
				return {
					success: false
				};
			}
		},
		
		// 开始打字效果
		startTyping(talkList) {
			if (this.isTyping) return;
			var that = this;
			this.isTyping = true;
			setTimeout(() => {
				if (this.currentIndex <= this.currentContent.length) {
					talkList[0].state = 1;
					talkList[0].content = this.currentContent.substring(0, this.currentIndex++);
					
					this.$forceUpdate();
					this.isTyping = false;
					this.startTyping(talkList);
				} else {
					if (that.currentMassage.is_end) {
						talkList[0].end = true;
						that.currentIndex = 0;
						that.currentContent = '';
						that.sendState = false;
					}
					this.isTyping = false;
				}
			}, this.typingInterval);
		},
		
		// 发送消息
		send(msg, talkList, currentModel, modelList) {
			if (this.sendState) {
				return false;
			}
			
			if (!msg) {
				this.$emit('showTip', {
					title: '请输入有效的内容',
					type: 'error',
					duration: '2300'
				});
				return false;
			}
			
			this.content = msg;
			this.sendState = true;
			
			// 添加用户消息
			talkList.unshift({
				content: this.content, // 消息内容
				type: 1, // 此为消息类别，设 1 为发出去的消息，0 为收到对方的消息,
				state: 1,
				icon: '/static/avatar.png',
			});
			
			// 获取当前选择的模型名称
			const currentModelName = modelList.find(model => model.value === currentModel)?.label || 'AI助手';
			
			// 添加机器人消息（空白，等待填充）
			talkList.unshift({
				content: '', // 消息内容
				type: 0, // 此为消息类别，设 1 为发出去的消息，0 为收到对方的消息,
				state: 0,
				end: false,
				icon: '/static/logo.png',
				modelName: currentModelName // 添加模型名称
			});
			
			// 发起请求
			this.requestAnswer(talkList, currentModel);
			
			return true;
		},
		
		// 请求AI回答
		requestAnswer(talkList, currentModel) {
			var that = this;
			const chunkRes = ChunkRes();
			const chatId = uni.getStorageSync('chatId');
			const sessionId = uni.getStorageSync('sessionId');
			const agentId = uni.getStorageSync('agentId');
			const agentSessionId = uni.getStorageSync('agentSessionId');
			let url = ''
			if (this.enableWebSearch) {
				url = `http://192.168.0.10/api/v1/agents/${agentId}/completions`
			} else {
				url = `http://192.168.0.10/api/v1/chats/${chatId}/completions`
			}
			const requestTask = uni.request({
				url,
				data: {
					question: this.enableWebSearch ? `模型:${currentModel},联网搜索:true|`+that.content : that.content,
					stream: true,
					session_id: this.enableWebSearch ? agentSessionId : sessionId,
					model: currentModel // 使用当前选择的模型
				},
				header: {
					Authorization: "Bearer ragflow-IyNmI3NjZjMDNiZTExZjA5YjQ5MDI0Mm"
				},
				method: 'post',
				enableChunked: true,  //流式输出需要设置enableChunked为true
				success: function (res) {
					const lastResTexts = chunkRes.onComplateReturn();
					for (let i = 0; i < lastResTexts.length; i++) {
						const item = JSON.parse(lastResTexts[i]);
						const data = item?.data;					
						if (data === true) {
							that.currentMassage = {
								result: '',
								is_end: true
							};
						}
						that.startTyping(talkList);
					}
				},
				fail: function (err) {
					console.error('请求失败:', err);
					that.sendState = false;
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
				}
			});

			// 监听流式输出
			requestTask.onChunkReceived(function (res) {
				const resTexts = chunkRes.onChunkReceivedReturn(res.data);	
				if (Array.isArray(resTexts)) {
					const dataArray = resTexts;
					for (let i = 0; i < dataArray.length; i++) {
						const item = JSON.parse(dataArray[i]);					
						console.log(item);
							
						const docs = item?.data?.reference?.doc_aggs || [];  // 参考资料列表
						if (docs.length > 0) {
							talkList[0].docs = docs;
						}
						const answer = item?.data?.answer;
						if (answer) {
							that.currentMassage = {
								result: answer,
								is_end: false,
							};
							that.currentContent = that.currentMassage.result;
						}
						that.startTyping(talkList);
					}
				}
			});
		}
	}
}
</script> 